#include <stdio.h>
#include <string.h>

#include <unistd.h>
#include <sys/param.h>
#include <sys/types.h>
#include <pwd.h>

#include "parse.h"
#include "jc.h"
#include "pool.h"
#include "encap.h"

String prompt_string = {{'\0'}, 0};

void print_banner(void)
{
    printf("\n");
    printf("================ Welcome to Yalnix Shell ================\n");
    printf("=================== by YousongZhou ======================\n");
    printf("\n\n");
}

void print_prompt(void)
{
    char *t_s;
    int len;

    t_s = getpwuid(getuid())->pw_dir;
    len = strlen(t_s);
    if (t_s[len - 1] == '/') {
        len--;
        t_s[len] = '\0';
    }
    prompt_string.len += sprintf(&prompt_string.str[prompt_string.len], "%s@", getlogin());
    prompt_string.len += ec_gethostname(&prompt_string.str[prompt_string.len], MAXHOSTNAMELEN);
    prompt_string.len += sprintf(&prompt_string.str[prompt_string.len], ":");
    ec_getcwd(&prompt_string.str[prompt_string.len], LINE_BUF_SIZE - prompt_string.len - 1);
    if (memcmp(&prompt_string.str[prompt_string.len], t_s, len) == 0) {
        // BUG HERE.
        prompt_string.len += sprintf(&prompt_string.str[prompt_string.len], "~%s", &prompt_string.str[prompt_string.len + len]);
    }
    else {
        prompt_string.len += strlen(&prompt_string.str[prompt_string.len]);
    }
    prompt_string.len += sprintf(&prompt_string.str[prompt_string.len], "%c ", strcmp(getlogin(), SUPERUSERNAME) == 0 ? '#' : '$');
    
    ec_tcsetpgrp(TERM_FILEDES, ysh_pid);
    printf("%s", prompt_string.str);

    prompt_string.len = 0;
    memset(prompt_string.str, (char)0, LINE_BUF_SIZE);
    prompt_string.str[0] = '\0';
}

void ysh_init(void)
{
    jc_init();
    p_init();
}

#ifdef DEBUG
void restore_back(void)
{
    execlp("bash", "bash", (char *)NULL); 
}
#endif


int main(int argc, char *argv[])
{
    ysh_init();
    print_banner();
#ifdef DEBUG
    printf("%d\n", getpid());
#endif
    while (TRUE) {
        // Something concerning job control may need to be printed before prompting.
        // Wait for processes in foreground process group to end.
        print_prompt();
        parse();
    }
    return 0;
}

